package com.kedacom.demo.modb.weibo.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.kedacom.demo.modb.weibo.model.Account;

/**
 * 用户帐号Dao
 * @author luocanfeng
 * @date 2013-1-14
 */
@Repository
public class TsoAccountDao extends TsoJdbcDaoSupport {

	private static final RowMapper<Account> accountRowMapper = new RowMapper<Account>() {

		@Override
		public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
			Account account = new Account();
			account.setCompanyMoid(rs.getString("company_moid"));
			account.setPublicCompanyAccount(rs.getBoolean("is_public"));
			account.setMoid(rs.getString("moid"));
			account.setEmail(rs.getString("email"));
			account.setE164(rs.getString("e164"));
			account.setPassword(rs.getString("password"));
			account.setJid(rs.getString("jid"));
			account.setRealName(rs.getString("name"));
			account.setSex(rs.getString("sex"));
			account.setSeat(rs.getString("seat"));
			account.setExtNum(rs.getString("ext_num"));
			account.setMobile(rs.getString("mobile_num"));
			account.setPosition(rs.getString("position"));
			account.setBrief(rs.getString("brief"));
			account.setCreatedAt(rs.getTimestamp("created_at"));
			return account;
		}
	};

	private String listAllSql = "select * from account order by company_moid,email";

	public List<Account> listAll() {
		return super.getJdbcTemplate().query(listAllSql, accountRowMapper);
	}

	private String copyAccountSql = "insert into account(company_moid,is_public,moid,email,e164,password,jid,name,sex,seat,ext_num,mobile_num,position,brief,created_at)"
			+ " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

	public void copy(Account account) {
		super.getJdbcTemplate().update(copyAccountSql, account.getCompanyMoid(), account.isPublicCompanyAccount(),
				account.getMoid(), account.getEmail(), account.getE164(), account.getPassword(), account.getJid(),
				account.getRealName(), account.getSex(), account.getSeat(), account.getExtNum(), account.getMobile(),
				account.getPosition(), account.getBrief(), account.getCreatedAt());
	}

	private String modifyBriefSql = "update account set brief=? where moid=?";

	public void modifyBrief(String moid, String brief) {
		super.getJdbcTemplate().update(modifyBriefSql, brief, moid);
	}

	private String getByMoidSql = "select * from account where moid=?";

	public Account getByMoid(String moid) {
		return super.getJdbcTemplate().queryForObject(getByMoidSql, accountRowMapper, moid);
	}

}
